package org.nemanjaristic.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.facebookapi.FacebookJaxbRestClient;
import com.google.code.facebookapi.FacebookWebappHelper;

/**
 * Servlet implementation class ServletDispatcher
 */
public class FBServlet extends HttpServlet {

	private static Logger logger = LoggerFactory.getLogger(FBServlet.class);

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FBServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		proccess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		proccess(request, response);
	}

	@SuppressWarnings("unchecked")
	private void proccess(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		String apiKey = "f8621c7b058da215191742e02975790b";
		String secretKey = "ec61fed4e45c60378b1e82524f733764";
		PrintWriter out = response.getWriter();
		FacebookJaxbRestClient client = new FacebookJaxbRestClient(apiKey, secretKey);
		if (client != null) {
			FacebookWebappHelper facebook = new FacebookWebappHelper(request, response, apiKey, secretKey, client);
			boolean log = facebook.requireLogin("http://127.0.0.1:8080/OPO/rec");
			session.setAttribute("client", client);
			if (log) {
				logger.info("Send user to log in.");
			}
			else {
				client.setCacheSessionKey(getSessionId(request, apiKey));
				response.sendRedirect("/OPO/rec");
			}
		}
		else
			out.print("Client is null.");
	}

	public String getSessionId(HttpServletRequest req, String apiKey) {
		String addition = "_session_key";
		String sessionId = "";
		Cookie[] cookies = req.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie c : cookies) {
				String name = c.getName();
				if (name.startsWith(apiKey)) {
					if (name.equals(apiKey + addition)) {
						sessionId = c.getValue();
						logger.debug("SESSION_ID = {}", sessionId);
					}
				}
			}
		}
		return sessionId;
	}
}
